package com.lanju.app.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.lanju.app.message.bean.B104Request;
import com.lanju.app.message.bean.B104Request.DetailBean;
import com.lanju.app.message.bean.BaseResponse;
import com.lanju.entity.Order;
import com.lanju.entity.OrderDetail;
import com.lanju.entity.Product;
import com.lanju.entity.ProductSku;
import com.lanju.entity.Shop;
import com.lanju.entity.Stock;
import com.lanju.entity.User;

/**
 * 门店下单
 * @author fly
 *
 */
@Service("B104Service")
public class B104Service extends BaseService<B104Request,BaseResponse>{

	private SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
	@Override
	public BaseResponse doService(B104Request request, User u) throws Exception {
		BaseResponse res = new BaseResponse();
		Shop shop = dao.get(Shop.class, request.getShopId());
		if(shop==null){
			res.setMessage("未找到对应的商店！");
			return res;
		}
//		List<Stock> stocks = dao.listByProp(Stock.class, "userId", u.getId());
		
		for(DetailBean bean : request.getDetails()){
			List<Object> params = new ArrayList<>();
			params.add(u.getId());
			params.add(bean.getSkuId());
			params.add(bean.getNumber());
			String sql = "SELECT COUNT(*) count FROM `stock` t WHERE t.`user_id`=? AND t.`prod_sku_id`=? AND (fixed_num_cur+add_num_cur)>? " ; 
			List<Map<String, Object>> list = dao.list(sql, params.toArray());
			if(list!=null && list.size()>0){
				Long obj = (Long)list.get(0).get("count");
				if(obj.longValue()==0L){
					ProductSku prodSku = dao.get(ProductSku.class, bean.getSkuId());
					if (prodSku==null){
						res.setMessage("该stock库存不足  " + bean.getSkuId());
						return res;
					}
					Product prod = dao.get(Product.class, bean.getProdId());
					res.setMessage(prod.getName() + prodSku.getUnit() + (prodSku.getTaste()==null?"":prodSku.getTaste()) + (prodSku.getColor()==null?"":prodSku.getColor()) + "库存不足！"  );
					return res;
				}
			}
				
		}
//		res = hasStock(stocks, request.getDetails());
//		if(!res.isSuccess()){
//			return res;
//		}
		
		Date now = new Date();
		Order order  = new Order();
		order.setId(newOrderId());
		order.setAddress(request.getAddress());
		order.setBusiId(u.getId());
		order.setBusiName(u.getName());
		order.setCarNum(request.getCarNum());
		order.setCreatedTime(now);
		order.setUpdatedTime(now);
		order.setCustName(request.getCustName());
		order.setDrawer(request.getDrawer());
		order.setFox(request.getFox());
		order.setOrderState(Order.STATE_INIT);
		order.setShopId(request.getShopId());		
		order.setShopName(shop.getName());
		order.setTel(request.getTel());
		order.setVisitId(request.getVisitId());
		BigDecimal amount = new BigDecimal(0);		
		for(DetailBean bean : request.getDetails()){
			ProductSku prodSku = dao.get(ProductSku.class, bean.getSkuId());
			Product prod = dao.get(Product.class, bean.getProdId());			
			OrderDetail detail = new OrderDetail();
			detail.setSkuId(bean.getSkuId());
			detail.setProdId(bean.getProdId());			
			detail.setNumber(bean.getNumber());
			detail.setOrderId(order.getId());
			detail.setUnit(prodSku.getUnit());
			detail.setUnitPrice(prodSku.getUnitPrice());
			detail.setPrice(prodSku.getUnitPrice());
			detail.setAmount(prodSku.getUnitPrice().multiply(new BigDecimal(bean.getNumber())));
			detail.setProdName(prod.getName());
			detail.setCreatedTime(now);
			detail.setUpdatedTime(now);
			dao.save(detail);
			amount = amount.add(detail.getAmount());			

			List<Object> params = new ArrayList<>();
			params.add(u.getId());
			params.add(bean.getSkuId());
			String sql = "SELECT * FROM `stock` t WHERE t.`user_id`=? AND t.`prod_sku_id`=? " ; 
			List<Stock> list = dao.list(sql, Stock.class, params.toArray());
			if (list!=null && list.size()>0){
				Stock stock = list.get(0);
				if(bean.getNumber()<=(stock.getFixedNumCur())){
					stock.setFixedNumCur(stock.getFixedNumCur()-bean.getNumber());
				}else {
					stock.setAddNumCur(stock.getFixedNumCur()+stock.getAddNumCur()-bean.getNumber());
					stock.setFixedNumCur(0);
				}
				dao.update(stock);
			}
			
		}
		order.setAmount(amount);
		dao.insert(order);		
		res.setSuccess(true);
		return res;
	}
	
	/**
	 * 判断库存
	 * @param stocks
	 * @param beans
	 * @return
	 */
//	private BaseResponse hasStock(List<Stock> stocks, List<DetailBean> beans ){
//		BaseResponse res = new BaseResponse();
//		for(DetailBean bean : beans){
//			ProductSku prodSku = dao.get(ProductSku.class, bean.getSkuId());
//			Product prod = dao.get(Product.class, bean.getProdId());
//			for(Stock stock: stocks){
//				if(bean.getSkuId().equals(stock.getProdSkuId())){
//					if(bean.getNumber()>(stock.getFixedNumCur()+stock.getAddNumCur())){
//						res.setMessage(prod.getName() + prodSku.getColor() + "  " + prodSku.getTaste() + "库存不足！"  );
//						return res;
//					}
//				}
//			}
//		}
//		res.setSuccess(true);
//		return res;
//	}

	private String newOrderId() {
		String id = sdf.format(new Date());
		id = id + "01";
		int count = dao.count(" SELECT COUNT(id) FROM `order` WHERE id like '"+id+"%' ");
		id = id + (count + 10000) + (int) (Math.random() * 10);
		return id;
	}
}
